package com.alipay.config;

import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.pojo.AliPayBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.FileCopyUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;

/** @author LENOVO */
@Configuration
public class AlipayConfig {
  /** 应用ID,您的APPID，收款账号既是您的APPID对应支付宝账号,开发时使用沙箱提供的APPID，生产环境改成自己的APPID */
  public static final String APPID = "你的沙箱APPID";
  /** 商户私钥，您的PKCS8格式RSA2私钥 */
  public static final String APP_PRIVATE_KEY = "你自己的私钥";
  /** 支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。 */
  public static final String ALIPAY_PUBLIC_KEY = "你自己的支付宝公钥，注意是支付宝公钥，不是应用公钥";
  /** 服务器异步通知页面路径 需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问 */
  public static final String NOTIFY_URL =
      "http://localhost:8080/alipay.trade.page.pay-JAVA-UTF-8/notify_url.jsp";
  /** 页面跳转同步通知页面路径 需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问(其实就是支付成功后返回的页面) */
  public static final String RETURN_URL =
      "http://localhost:8080/alipay.trade.page.pay-JAVA-UTF-8/return_url.jsp";
  /** 签名方式 */
  public static final String SIGN_TYPE = "RSA2";
  /** 设置请求格式 */
  public static final String FORMAT = "json";
  /** 字符编码格式 */
  public static final String CHARSET = "utf-8";
  /** 支付宝网关(沙箱网关:https://openapi.alipaydev.com/gateway.do) */
  public static final String GATEWAY_URL = "https://openapi.alipay.com/gateway.do";
  /** 日志路径 */
  public static final String LOG_PATH =System.getProperty("user.dir");

  @Value("${custom.http.proxyHost}")
  private String proxyHost;

  @Value("${custom.http.proxyPort}")
  private int proxyPort;

  @Value("${spring.profiles.active}")
  private String activeEnv;

  @Resource private AliPayBean aliPayBean;

  @Bean(name = {"alipayClient"})
  public AlipayClient alipayClientService() throws Exception {
    CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
    // 设置网关地址
    certAlipayRequest.setServerUrl(GATEWAY_URL);
    // 设置应用Id
    certAlipayRequest.setAppId(APPID);
    // 设置应用私钥
    certAlipayRequest.setPrivateKey(APP_PRIVATE_KEY);
    // 设置请求格式，固定值json
    certAlipayRequest.setFormat(FORMAT);
    // 设置字符集
    certAlipayRequest.setCharset(CHARSET);
    // 设置签名方式
    certAlipayRequest.setSignType(SIGN_TYPE);
    // 如果是生产环境或者预演环境，则使用代理模式
    if ("prod".equals(activeEnv) || "stage".equals(activeEnv) || "test".equals(activeEnv)) {
      // 设置应用公钥证书路径
      certAlipayRequest.setCertContent(getCertContentByPath(aliPayBean.getAppCertPath()));
      // 设置支付宝公钥证书路径
      certAlipayRequest.setAlipayPublicCertContent(
          getCertContentByPath(aliPayBean.getAlipayCertPath()));
      // 设置支付宝根证书路径
      certAlipayRequest.setRootCertContent(
          getCertContentByPath(aliPayBean.getAlipayRootCertPath()));
      certAlipayRequest.setProxyHost(proxyHost);
      certAlipayRequest.setProxyPort(proxyPort);

    } else {
      // local
      String serverPath = this.getClass().getResource("/").getPath();
      // 设置应用公钥证书路径
      certAlipayRequest.setCertPath(serverPath + aliPayBean.getAppCertPath());
      // 设置支付宝公钥证书路径
      certAlipayRequest.setAlipayPublicCertPath(serverPath + aliPayBean.getAlipayCertPath());
      // 设置支付宝根证书路径
      certAlipayRequest.setRootCertPath(serverPath + aliPayBean.getAlipayRootCertPath());
    }
    return new DefaultAlipayClient(certAlipayRequest);
  }

  public String getCertContentByPath(String name) {
    InputStream inputStream = null;
    String content = null;
    try {
      inputStream = this.getClass().getClassLoader().getResourceAsStream(name);
      content = new String(FileCopyUtils.copyToByteArray(inputStream));
    } catch (Exception e) {
      e.printStackTrace();
    }
    return content;
  }
  /**
   * 写日志，方便测试（看网站需求，也可以改成把记录存入数据库）
   *
   * @param sWord 要写入日志里的文本内容
   */
  public static void logResult(String sWord) {
    FileWriter writer = null;
    try {
      String fileName = "logFile";
      File file = new File(LOG_PATH,fileName);
      if (!file.exists()){
        file.mkdirs();
      }
      String targetFile = file.getAbsolutePath();
      writer = new FileWriter(targetFile + "alipay_log_" + System.currentTimeMillis() + ".txt");
      writer.write(sWord);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (writer != null) {
        try {
          writer.close();
        } catch (IOException e) {

          e.printStackTrace();
        }
      }
    }
  }
}
